package com.cyt.wx.service.impl;

import cn.hutool.core.util.StrUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.BaseConstant;
import com.cyt.base.util.DictCode;
import com.cyt.base.util.ErrorCode;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.wx.dao.WxApplyMenuDao;
import com.cyt.wx.model.po.WxApply;
import com.cyt.wx.model.po.WxApplyMenu;
import com.cyt.wx.model.vo.WxApplyMenuVo;
import com.cyt.wx.model.vo.WxApplyVo;
import com.cyt.wx.service.WxApplyMenuService;
import com.cyt.wx.service.WxApplyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

/**
 * 微信管理-应用菜单Service层实现类
 *
 * @author shengQiang Yu
 * @date 2019-8-9 10:22:14
 */
@Service("wxApplyMenuService")
public class WxApplyMenuServiceImpl extends BaseServiceImpl<WxApplyMenu> implements WxApplyMenuService {

    @Resource
    private WxApplyMenuDao wxApplyMenuDao;
    @Resource
    private WxApplyService wxApplyService;
    @Autowired
    public void setBaseDao(WxApplyMenuDao wxApplyMenuDao) {
        this.baseDao = wxApplyMenuDao;
    }

    /**
     * 查询对象集合
     *
     * @param wxApplyMenuVo 对象
     * @return List 对象集合
     * @author shengQiang Yu
     * @date 2019-8-9 10:22:14
     */
    @Override
    public List<WxApplyMenu> listExample(WxApplyMenuVo wxApplyMenuVo) {
        Example example = new Example(WxApplyMenu.class);
        example.setOrderByClause(" menu_grade asc, sort desc");
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(wxApplyMenuVo.getApplyUseId())) {
            criteria.andLike("applyUseId", wxApplyMenuVo.getApplyUseId());
        }
        if (StringUtils.isNotBlank(wxApplyMenuVo.getParentId())) {
            criteria.andLike("parentId", wxApplyMenuVo.getParentId());
        }
        if (StringUtils.isNotBlank(wxApplyMenuVo.getMenuName())) {
            criteria.andLike("menuName", "%" + wxApplyMenuVo.getMenuName() + "%");
        }
        if (StringUtils.isNotBlank(wxApplyMenuVo.getMenuType())) {
            criteria.andIn("menuType", Arrays.asList(wxApplyMenuVo.getMenuType().split(",")));
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        return wxApplyMenuDao.selectByExample(example);
    }

    /**
     * 分页查询
     *
     * @param wxApplyMenuVo 接受参数对象
     * @param pageNum       分页数
     * @param pageSize      每页显示条数
     * @return ReturnResult
     * @author shengQiang Yu
     * @date 2019-8-9 10:22:14
     */
    @Override
    public ReturnResult page(WxApplyMenuVo wxApplyMenuVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" sort desc");
        List<WxApplyMenu> list = listExample(wxApplyMenuVo);
        PageInfo<WxApplyMenu> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 添加或更新
     *
     * @param wxApplyMenuVo 参数接受对象
     * @param sysUser       当前用户
     * @return ReturnResult
     * @author shengQiang Yu
     * @date 2019-8-9 10:22:14
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(WxApplyMenuVo wxApplyMenuVo, SysUser sysUser) {
        if (StrUtil.isEmpty(wxApplyMenuVo.getId())) {
            WxApplyMenu wxApplyMenu = new WxApplyMenu(sysUser);
            wxApplyMenu.setApplyUseId(wxApplyMenuVo.getApplyUseId());
            wxApplyMenu.setParentId(wxApplyMenuVo.getParentId());
            wxApplyMenu.setMenuName(wxApplyMenuVo.getMenuName());
            wxApplyMenu.setMenuType(wxApplyMenuVo.getMenuType());
            wxApplyMenu.setMenuUrl(wxApplyMenuVo.getMenuUrl());
            wxApplyMenu.setMenuIcon(wxApplyMenuVo.getMenuIcon());
            wxApplyMenu.setMenuGrade(initMenuGrade(wxApplyMenu.getParentId()));
            wxApplyMenu.setPermission(wxApplyMenuVo.getPermission());
            wxApplyMenu.setSort(wxApplyMenuVo.getSort());
            wxApplyMenuDao.insert(wxApplyMenu);
            return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_INSERT);
        } else {
            WxApplyMenu wxApplyMenu = wxApplyMenuDao.selectByPrimaryKey(wxApplyMenuVo.getId());
            wxApplyMenu.setParentId(wxApplyMenuVo.getParentId());
            wxApplyMenu.setMenuName(wxApplyMenuVo.getMenuName());
            wxApplyMenu.setMenuType(wxApplyMenuVo.getMenuType());
            wxApplyMenu.setMenuUrl(wxApplyMenuVo.getMenuUrl());
            wxApplyMenu.setMenuIcon(wxApplyMenuVo.getMenuIcon());
            wxApplyMenu.setMenuGrade(initMenuGrade(wxApplyMenu.getParentId()));
            wxApplyMenu.setPermission(wxApplyMenuVo.getPermission());
            wxApplyMenu.setSort(wxApplyMenuVo.getSort());
            wxApplyMenu.setUpdateTime(new Date());
            wxApplyMenu.setUpdateUser(sysUser.getId());
            wxApplyMenuDao.updateByPrimaryKey(wxApplyMenu);
            syncUpdateChildMenu(wxApplyMenu.getId(), wxApplyMenu.getMenuGrade());
            return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_UPDATE);
        }
    }

    private void syncUpdateChildMenu(String id, Integer menuGrade) {
        WxApplyMenuVo wxApplyMenuVo = new WxApplyMenuVo();
        wxApplyMenuVo.setParentId(id);
        List<WxApplyMenu> wxApplyMenuList = this.listExample(wxApplyMenuVo);
        if (CollectionUtils.isNotEmpty(wxApplyMenuList)) {
            for (WxApplyMenu wxApplyMenu : wxApplyMenuList) {
                wxApplyMenu.setMenuGrade(menuGrade + 1);
                wxApplyMenuDao.updateByPrimaryKey(wxApplyMenu);
                syncUpdateChildMenu(wxApplyMenu.getId(), wxApplyMenu.getMenuGrade());
            }
        }
    }

    private Integer initMenuGrade(String parentId) {
        if (StringUtils.isBlank(parentId)) {
            return 1;
        } else {
            WxApplyMenu wxApplyMenu = wxApplyMenuDao.selectByPrimaryKey(parentId);
            return wxApplyMenu.getMenuGrade() + 1;
        }
    }

    /**
     * 根据条件逻辑删除
     *
     * @param wxApplyMenuVo 参数接受对象
     * @param sysUser       当前用户
     * @return ReturnResult
     * @author shengQiang Yu
     * @date 2019-8-9 10:22:14
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(WxApplyMenuVo wxApplyMenuVo, SysUser sysUser) {
        //要修改的字段
        WxApplyMenu wxApplyMenu = new WxApplyMenu();
        wxApplyMenu.setRemoveTag(DictCode.BASE_REMOVE_TAG_DELETE);
        wxApplyMenu.setUpdateUser(sysUser.getId());
        wxApplyMenu.setUpdateTime(new Date());
        //筛选条件
        Example example = new Example(WxApplyMenu.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(wxApplyMenuVo.getId())) {
            criteria.andIn("id", Arrays.asList(wxApplyMenuVo.getId().split(",")));
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        wxApplyMenuDao.updateByExampleSelective(wxApplyMenu, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 获取菜单树
     *
     * @param wxApplyMenuVo 参数接受对象
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-8-15 17:15
     */
    @Override
    public ReturnResult dTreeList(WxApplyMenuVo wxApplyMenuVo) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<WxApplyMenu> wxApplyMenuList = removeChild(wxApplyMenuVo.getId(), this.listExample(wxApplyMenuVo));
        for (WxApplyMenu wxApplyMenu : wxApplyMenuList) {
            Map<String, Object> resultMap = new LinkedHashMap<>();
            resultMap.put("id", wxApplyMenu.getId());
            resultMap.put("title", wxApplyMenu.getMenuName());
            resultMap.put("parentId", StringUtils.isBlank(wxApplyMenu.getParentId()) ? "0" : wxApplyMenu.getParentId());
            resultMap.put("isLast", wxApplyMenu.getMenuGrade() == 2);
            Map<String, String> map = new LinkedHashMap<>();
            map.put("type", "0");
            map.put("isChecked", "0");
            List<Map<String, String>> checkArrList = new ArrayList<>();
            checkArrList.add(map);
            resultMap.put("checkArr", checkArrList);
            resultList.add(resultMap);
        }
        return new ReturnResult(resultList);
    }

    private List<WxApplyMenu> removeChild(String id, List<WxApplyMenu> wxApplyMenuList) {
        Iterator iterator = wxApplyMenuList.iterator();
        while (iterator.hasNext()) {
            WxApplyMenu wxApplyMenu = (WxApplyMenu) iterator.next();
            if (wxApplyMenu.getParentId() != null && wxApplyMenu.getParentId().equals(id)) {
                if (hasChild(wxApplyMenu.getId(), wxApplyMenuList)) {
                    removeChild(wxApplyMenu.getId(), wxApplyMenuList);
                } else {
                    iterator.remove();
                }
            }
        }
        return wxApplyMenuList;
    }

    private boolean hasChild(String id, List<WxApplyMenu> wxApplyMenuList) {
        for (WxApplyMenu wxApplyMenu : wxApplyMenuList) {
            if (wxApplyMenu.getParentId().equals(id)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 根据用户id获取菜单
     *
     * @param userId 用户id
     * @return List<WxApplyMenuVo>
     * @author shengQiang yu
     * @date 2019-08-27 15:37
     */
    @Override
    public List<WxApplyMenuVo> selectByUserId(String userId) {
        List<WxApply> wxApplyList = wxApplyService.selectListByCondition(new WxApplyVo(userId));
        List<WxApply> resultApplyList=new ArrayList<>();
        for(WxApply wxApply:wxApplyList){
            if (wxApply.getUseDay().getTime() >= System.currentTimeMillis()) {
                resultApplyList.add(wxApply);
            }
        }
        //获取菜单
        List<WxApplyMenu> wxApplyMenuList = this.selectByCondition(new WxApplyMenuVo(userId,resultApplyList));
        //菜单分类
        List<WxApplyMenu> wxApplyMenuList1 = new ArrayList<>();
        List<WxApplyMenu> wxApplyMenuList2 = new ArrayList<>();
        List<WxApplyMenu> wxApplyMenuList3 = new ArrayList<>();
        for (WxApplyMenu wxApplyMenu : wxApplyMenuList) {
            int menuGrade = wxApplyMenu.getMenuGrade();
            switch (menuGrade) {
                case 1:
                    wxApplyMenuList1.add(wxApplyMenu);
                    break;
                case 2:
                    wxApplyMenuList2.add(wxApplyMenu);
                    break;
                case 3:
                    wxApplyMenuList3.add(wxApplyMenu);
                    break;
            }
        }
        //菜单关联
        List<WxApplyMenuVo> wxApplyMenuVoList = new ArrayList<>();
        for (WxApplyMenu wxApplyMenu1 : wxApplyMenuList1) {
            WxApplyMenuVo child1 = transformToVo(wxApplyMenu1);
            List<WxApplyMenuVo> childList1 = new ArrayList<>();
            for (WxApplyMenu wxApplyMenu2 : wxApplyMenuList2) {
                if (wxApplyMenu1.getId().equals(wxApplyMenu2.getParentId())) {
                    WxApplyMenuVo child2 = transformToVo(wxApplyMenu2);
                    List<WxApplyMenuVo> childList2 = new ArrayList<>();
                    for (WxApplyMenu wxApplyMenu3 : wxApplyMenuList3) {
                        if (wxApplyMenu2.getId().equals(wxApplyMenu3.getParentId())) {
                            childList2.add(transformToVo(wxApplyMenu3));
                        }
                    }
                    child2.setChildList(childList2);
                    childList1.add(child2);
                }
            }
            child1.setChildList(childList1);
            wxApplyMenuVoList.add(child1);
        }
        return wxApplyMenuVoList;
    }

    private WxApplyMenuVo transformToVo(WxApplyMenu wxApplyMenu) {
        WxApplyMenuVo wxApplyMenuVo = new WxApplyMenuVo();
        wxApplyMenuVo.setId(wxApplyMenu.getId());
        if (StrUtil.isNotEmpty(wxApplyMenu.getMenuUrl())) {
            if (wxApplyMenu.getMenuUrl().contains("?")) {
                wxApplyMenuVo.setMenuUrl(wxApplyMenu.getMenuUrl() + "&applyId=" + wxApplyMenu.getApplyId());
            } else {
                wxApplyMenuVo.setMenuUrl(wxApplyMenu.getMenuUrl() + "?applyId=" + wxApplyMenu.getApplyId());
            }

        }

        wxApplyMenuVo.setMenuName(wxApplyMenu.getMenuName());
        wxApplyMenuVo.setMenuIcon(wxApplyMenu.getMenuIcon());
        return wxApplyMenuVo;
    }

    /**
     * 根据条件查询
     *
     * @param wxApplyMenuVo 参数接受对象
     * @return List<WxApplyMenuVo>
     * @author shengQiang Yu
     * @date 2019-8-16 8:45:15
     */
    @Override
    public List<WxApplyMenu> selectByCondition(WxApplyMenuVo wxApplyMenuVo) {
        return wxApplyMenuDao.selectByCondition(wxApplyMenuVo);
    }
}